package com.cloudinnov.logic.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.cloudinnov.dao.AlarmWorkOrdersDao;
import com.cloudinnov.dao.AttachDao;
import com.cloudinnov.dao.AuthUserDao;
import com.cloudinnov.dao.EquipmentBomsDao;
import com.cloudinnov.dao.EquipmentFaultChannelDao;
import com.cloudinnov.dao.EquipmentPointsDao;
import com.cloudinnov.dao.EquipmentsAttrDao;
import com.cloudinnov.dao.EquipmentsCategoriesDao;
import com.cloudinnov.dao.EquipmentsDao;
import com.cloudinnov.dao.SectionDao;
import com.cloudinnov.logic.EquipmentsLogic;
import com.cloudinnov.model.AlarmWorkOrders;
import com.cloudinnov.model.Attach;
import com.cloudinnov.model.AuthUsers;
import com.cloudinnov.model.Companies;
import com.cloudinnov.model.EquipmentArea;
import com.cloudinnov.model.EquipmentBoms;
import com.cloudinnov.model.EquipmentFaultChannel;
import com.cloudinnov.model.EquipmentPoints;
import com.cloudinnov.model.Equipments;
import com.cloudinnov.model.EquipmentsAttr;
import com.cloudinnov.model.EquipmentsCategories;
import com.cloudinnov.model.Section;
import com.cloudinnov.model.TreeObject;
import com.cloudinnov.utils.CodeUtil;
import com.cloudinnov.utils.CommonUtils;
import com.cloudinnov.utils.JudgeNullUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.zxing.WriterException;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisException;
import scala.Int;

/**
 * @author guochao
 * @date 2016年2月17日上午11:53:48
 * @email chaoguo@cloudinnov.com
 * @remark 设备业务层实现
 * @version
 */
@Service("equipmentsLogic")
public class EquipmentsLogicImpl extends BaseLogicImpl<Equipments> implements EquipmentsLogic {
	private static final Logger LOG = LoggerFactory.getLogger(EquipmentsLogicImpl.class);
	private int digit = 5;
	public static int CURRENT_STATE_FAULT = 2;
	private static final String POINT_NAME = "point:";
	private static final String VALUE_NAME = ":value";
	private static final String REALTIME_SPLITTER_LEVEL1 = ",";
	private static final int REALTIME_TIME_OUT_SECOND = 60;
	private static final int REALTIME_TIME_OUT_MILL = 1000;

	// 设备分类常量
	private static final String SBCHZTCQ = "SBCHZTCQ"; // 双波长探测器报警
	private static final String FBSGWGX = "FBSGWGX"; // 感温光纤报警
	private static final String SDBJAN = "SDBJAN"; // 手动火灾报警

	@Autowired
	private JedisPool jedisPool;
	@Autowired
	private EquipmentsDao equipmentsDao;
	@Autowired
	private AlarmWorkOrdersDao alarmWorkOrdersDao;
	@Autowired
	private AuthUserDao authUserDao;
	@Autowired
	private AttachDao attachDao;
	@Autowired
	private EquipmentsAttrDao equipmentsAttrDao;
	@Autowired
	private EquipmentBomsDao equipmentBomsDao;
	@Autowired
	private EquipmentPointsDao equipmentPointsDao;
	@Autowired
	private EquipmentFaultChannelDao equipmentFaultChannelDao;
	@Autowired
	private EquipmentsCategoriesDao equipmentsCateDao;
	@Autowired
	private SectionDao sectionDao;

	public int save(Equipments equipment) {
		String equipmentCode = CodeUtil.equipmentCode(digit);// 生成设备code
		equipment.setCode(equipmentCode);
		equipment.setStatus(CommonUtils.STATUS_NORMAL);
		List<EquipmentsAttr> list = null;
		if (equipment.getAttrInfo() != null) {
			list = JSON.parseArray(equipment.getAttrInfo(), EquipmentsAttr.class);
		}
		EquipmentsAttr eqAttrModel = new EquipmentsAttr();
		int result = equipmentsDao.insert(equipment);
		if (result == 1) {
			if (list.size() > 0 && list != null) {
				for (EquipmentsAttr eqAttrInfo : list) {
					eqAttrModel.setEquipmentCode(equipmentCode);
					eqAttrModel.setCustomTag(eqAttrInfo.getCustomTag());
					eqAttrModel.setName(eqAttrInfo.getName());
					eqAttrModel.setValue(eqAttrInfo.getValue());
					eqAttrModel.setStatus(CommonUtils.STATUS_NORMAL);
					equipmentsAttrDao.insert(eqAttrModel);
				}
			}
			// 保存设备二维码
			Attach attach = new Attach();
			attach.setObjectCode(equipmentCode);
			String fileName = CommonUtils.getUUID();
			attach.setUrl(CommonUtils.generateFileName(fileName));
			attach.setFileType(AttachLogicImpl.ATTACH_FILETYPE_IMAGE);
			attach.setType(AttachLogicImpl.ATTACH_EQUIPMENT_TYPE);
			attachDao.insert(attach);
			Map<String, Object> params = new HashMap<String, Object>();
			try {
				params.put("object", CommonUtils.QR_EQUIPMENT);
				params.put("code", equipmentCode);
				CommonUtils.generateQRCode(null, fileName, null,
						CommonUtils.WEB_ADDRESS_FRONTEND_USER + CommonUtils.QR_EQUIPMENT + "/detail/" + equipmentCode
								+ "?object=" + CommonUtils.QR_EQUIPMENT + "&code=" + equipmentCode);
			} catch (WriterException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return equipmentsDao.insertInfo(equipment);
		} else {
			return 0;
		}
	}

	public int delete(Equipments equipment) {
		int result = equipmentsDao.deleteByCondition(equipment);
		equipmentsAttrDao.deleteInfoByEquCode(equipment.getCode());
		return result;
	}

	public int update(Equipments equipment) {
		List<EquipmentsAttr> list = JSON.parseArray(equipment.getAttrInfo(), EquipmentsAttr.class);// 将前台传来的JSON类型的数据转换成List
		EquipmentsAttr eqAttrModel = new EquipmentsAttr();// 创建设备属性对象
		eqAttrModel.setEquipmentCode(equipment.getCode());
		int result = equipmentsDao.updateByCondition(equipment);
		if (result == 1) {
			List<EquipmentsAttr> attrList = equipmentsAttrDao.selectListByEquipmentCode(eqAttrModel.getEquipmentCode());
			if (list.size() > attrList.size()) {
				list.addAll(attrList);
			}
			equipmentsAttrDao.deleteInfoByEquCode(eqAttrModel.getEquipmentCode());
			for (EquipmentsAttr eqAttrInfo : list) {
				eqAttrModel.setEquipmentCode(equipment.getCode());
				eqAttrModel.setCustomTag(eqAttrInfo.getCustomTag());
				eqAttrModel.setName(eqAttrInfo.getName());
				eqAttrModel.setValue(eqAttrInfo.getValue());
				equipmentsAttrDao.insert(eqAttrModel);
			}
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public int selectEquipmentTotalByCustomerCode(String comCode) {
		return equipmentsDao.selectEquipmentTotalByCustomerCode(comCode);
	}

	@Override
	public List<Equipments> listByCustomer(Equipments equipments) {
		return equipmentsDao.listByCustomer(equipments);
	}

	@Override
	public Page<Equipments> search(int index, int size, String country, String province, String city,
			String categoryCode, String key, String sectionCode, String language, String type) {
		Map<String, Object> map = new HashMap<String, Object>();

		Page<Equipments> list = null;

		map.put("country", country);
		map.put("province", province);
		map.put("city", city);
		map.put("sectionCode", sectionCode);
		map.put("language", language);
		map.put("name", key);
		if (type != null) {
			if (type.equals(CommonUtils.SECTION_TYPE_TUNNEL)) {
				map.put("type", type);
			} else if (type.equals("expy")) {
				map.put("type", type);
			} else {
				map.put("type", "");
			}
		} else {
			map.put("type", "");
		}
		if (CommonUtils.isNotEmpty(categoryCode)) {// 查询当前分类以及所有子分类下的设备
			EquipmentsCategories parentModel = new EquipmentsCategories();
			parentModel.setCode(categoryCode);
			parentModel.setLanguage(language);
			parentModel = equipmentsCateDao.selectEntityByCondition(parentModel);
			if (parentModel != null) {
				List<EquipmentsCategories> chilrenCates = equipmentsCateDao.selectListByParentId(parentModel.getId());
				String[] equCateCodes = new String[chilrenCates.size() + 1];
				equCateCodes[0] = parentModel.getCode();
				if (JudgeNullUtil.iList(chilrenCates)) {
					for (int i = 0; i < chilrenCates.size(); i++) {
						equCateCodes[i + 1] = chilrenCates.get(i).getCode();
					}
				}
				map.put("categoryCodes", equCateCodes);
				PageHelper.startPage(index, size);
				list = equipmentsDao.search(map);
			}
		} else {
			 PageHelper.startPage(index, size);
			 list = equipmentsDao.search(map);
		}

		// PageHelper.startPage(index, size);
		// Page<Equipments> list = equipmentsDao.search(map);

		return list;
	}

	@Override
	public int saveOtherLanguage(Equipments equipment) {
		return equipmentsDao.insertInfo(equipment);
	}

	@Override
	public Map<String, Object> selectEquipmentState(Equipments equipments) {
		Equipments model = equipmentsDao.selectEntityByCondition(equipments);
		Map<String, Object> map = new HashMap<String, Object>();
		if (model.getCurrentState() == CommonUtils.EQU_STATE_FAULT) {
			AlarmWorkOrders alarm = new AlarmWorkOrders();
			alarm.setEquipmentCode(model.getCode());
			alarm = alarmWorkOrdersDao.selectEntityByCondition(alarm);
			map.put(alarm.getCode(), alarm.getStatusName());
		}
		return map;
	}

	@Override
	public int selectEquipmentStates(Companies company) {
		return equipmentsDao.selectEquipmentsStateByCondition(company);
	}

	@Override
	public int updateOtherLanguage(Equipments equipment) {
		return equipmentsDao.updateInfoByCondition(equipment);
	}

	@Override
	public Page<Equipments> selectEquipmentsByUser(Equipments equipments, int index, int size) {
		PageHelper.startPage(index, size);
		Page<Equipments> list = (Page<Equipments>) equipmentsDao.selectEquipmentsByUser(equipments);
		return list;
	}

	@Override
	public List<Equipments> selectEquipmentsByUser(Equipments equipments) {
		List<Equipments> list = equipmentsDao.selectEquipmentsByUser(equipments);
		return list;
	}

	@Override
	public List<Equipments> listByCustomers(String language, String[] codes) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("language", language);
		map.put("codes", codes);
		return equipmentsDao.listByCustomers(map);
	}

	@Override
	public int selectEquipmentListByOemCode(Companies company) {
		return equipmentsDao.selectEquipmentListByOemCode(company);
	}

	@Override
	public List<Equipments> getEquipmentListByState(Companies company) {
		return equipmentsDao.getEquipmentListByState(company);
	}

	@Override
	public Equipments select(Equipments equipment) {
		EquipmentsAttr equAttr = new EquipmentsAttr();
		equAttr.setEquipmentCode(equipment.getCode());
		Equipments model = equipmentsDao.selectEntityByCondition(equipment);
		if (model != null) {
			if (model.getCustomerPerson() != null) {
				List<AuthUsers> users = new ArrayList<AuthUsers>();
				String[] userCode = String.valueOf(model.getCustomerPerson()).split(",");
				for (int i = 0; i < userCode.length; i++) {
					AuthUsers user = new AuthUsers();
					user.setCode(userCode[i]);
					user.setLanguage(equipment.getLanguage());
					users.add(authUserDao.selectEntityByCondition(user));
				}
				model.setCustomerPersons(users);
			} else if (model.getOemPerson() != null) {
				List<AuthUsers> users = new ArrayList<AuthUsers>();
				String[] userCode = String.valueOf(model.getOemPerson()).split(",");
				for (int i = 0; i < userCode.length; i++) {
					AuthUsers user = new AuthUsers();
					user.setCode(userCode[i]);
					user.setLanguage(equipment.getLanguage());
					users.add(authUserDao.selectEntityByCondition(user));
				}
				model.setOemPersons(users);
			}
			List<EquipmentsAttr> equAttrList = equipmentsAttrDao.selectListByEquipmentCode(equAttr.getEquipmentCode());
			model.setAttrInfo(JSON.toJSONString(equAttrList));
		}
		return model;
	}

	/**
	 * 根据路段code查询设备
	 */
	@Override
	public List<Equipments> selectEquListBySectionCode(Equipments equipments) {
		List<Equipments> list = equipmentsDao.selectEquListBySectionCode(equipments);
		return list;
	}

	@Override
	public int copyEquipments(Equipments equipments) {
		int returnCode = 0;
		Equipments model = equipmentsDao.selectEntityByCondition(equipments);
		Map<String, Object> params = new HashMap<>();
		if (model != null) {
			String oldEquCode = model.getCode();
			params.put("oldEquCode", oldEquCode);
			for (int i = 1; i <= equipments.getCount(); i++) {
				String newEquipmentCode = CodeUtil.equipmentCode(digit);// 生成设备code
				params.put("newEquipmentCode", newEquipmentCode);
				model.setCode(newEquipmentCode);
				model.setName(model.getName() + "#" + i);
				// 插入设备
				returnCode = equipmentsDao.insert(model);
				if (returnCode == CommonUtils.SUCCESS_NUM) {
					returnCode = equipmentsDao.insertInfo(model);
				}
				// 插入成功后再插入子项
				if (returnCode == CommonUtils.SUCCESS_NUM) {
					EquipmentsAttr equAttrModel = new EquipmentsAttr();
					equAttrModel.setEquipmentCode((String) params.get("oldEquCode"));
					// 查询设备附加属性列表
					List<EquipmentsAttr> equAttrList = equipmentsAttrDao.selectListByCondition(equAttrModel);
					if (equAttrList != null && equAttrList.size() > 0) {
						for (EquipmentsAttr equipmentsAttr : equAttrList) {
							equipmentsAttr.setCode(CodeUtil.equipmentCateAttrCode(digit));
							equipmentsAttr.setEquipmentCode(newEquipmentCode);
						}
						// 插入设备附件属性新列表
						params.put("list", equAttrList);
						equipmentsAttrDao.insertBatch(params);
					}
					EquipmentBoms equBomModel = new EquipmentBoms();
					equBomModel.setEquipmentCode((String) params.get("oldEquCode"));
					// 查询设备元件列表
					List<EquipmentBoms> equipmentBomsList = equipmentBomsDao.selectListByCondition(equBomModel);
					if (equipmentBomsList != null && equipmentBomsList.size() > 0) {
						for (EquipmentBoms equipmentBom : equipmentBomsList) {
							equipmentBom.setCode(CodeUtil.equipmentBomCode(digit));
							equipmentBom.setEquipmentCode(newEquipmentCode);
						}
						// 插入设备元件新列表
						params.put("list", equipmentBomsList);
						equipmentBomsDao.insertBatch(params);
					}
					EquipmentPoints equPointModel = new EquipmentPoints();
					equPointModel.setEquipmentCode((String) params.get("oldEquCode"));
					// 查询设备点位列表
					List<EquipmentPoints> equPointsList = equipmentPointsDao.selectListByCondition(equPointModel);
					if (equPointsList != null && equPointsList.size() > 0) {
						for (EquipmentPoints equPoint : equPointsList) {
							equPoint.setCode(CodeUtil.pointCode(digit, equPoint.getType()));
							equPoint.setEquipmentCode(newEquipmentCode);
						}
						// 插入设备点位新列表
						params.put("list", equPointsList);
						equipmentPointsDao.insertBatch(params);
					}
					EquipmentFaultChannel equFaultChannelModel = new EquipmentFaultChannel();
					equFaultChannelModel.setEquipmentCode((String) params.get("oldEquCode"));
					// 查询设备通道列表
					List<EquipmentFaultChannel> equFaultChannelList = equipmentFaultChannelDao
							.selectListByCondition(equFaultChannelModel);
					if (equFaultChannelList != null && equFaultChannelList.size() > 0) {
						for (EquipmentFaultChannel equFaultChannel : equFaultChannelList) {
							equFaultChannel.setCode(CodeUtil.equipmentFaultChannelCode(digit));
							equFaultChannel.setEquipmentCode(newEquipmentCode);
						}
						// 插入设备故障通道新列表
						params.put("list", equFaultChannelList);
						equipmentFaultChannelDao.insertBatch(params);
					}
				}
			}
		}
		return returnCode;
	}

	@Override
	public List<Equipments> selectMainMonitor(Equipments equipments) {
		List<Equipments> list = equipmentsDao.selectMainMonitor(equipments);
		List<Equipments> stateList = equipmentsDao.selectEquipmentStateList(equipments);
		if (list != null && !list.isEmpty()) {
			for (Equipments equModel : list) {
				for (Equipments state : stateList) {
					if (CommonUtils.isNotEmpty(equModel.getCategoryCode())
							&& CommonUtils.isNotEmpty(state.getCategoryCode())
							&& equModel.getCategoryCode().equals(state.getCategoryCode())) {
						if (state.getCurrentState() == CommonUtils.EQU_STATE_OFFLINE) {
							equModel.setEquDisConnectSum(equModel.getEquDisConnectSum() + 1);
						} else if (state.getCurrentState() == CommonUtils.EQU_STATE_FAULT) {
							equModel.setEquDisConnectSum(equModel.getEquFaultSum() + 1);
						}
					}
				}
			}
		}
		return list;
	}

	@Override
	public List<Equipments> selectEquListByCateCode(Equipments equipments) {
		return equipmentsDao.selectEquListByCateCode(equipments);
	}

	@Override
	public Page<Equipments> selectEquipmentsInfo(int index, int size, Equipments equipments, boolean b) {
		PageHelper.startPage(index, size);
		Page<Equipments> list = (Page<Equipments>) equipmentsDao.selectEquipmentsInfo(equipments);
		return list;
	}

	@Override
	public Page<Equipments> selectInfoQuipments(Equipments equipments, int index, int size) {
		PageHelper.startPage(index, size);
		Page<Equipments> list = (Page<Equipments>) equipmentsDao.selectInfoQuipments(equipments);// 查询情报板类型的设备
		for (Equipments equipment : list) {
			Map<String, Object> map = new HashMap<String, Object>();
			String equipmentCode = equipment.getCode();// 获取设备编码
			List<EquipmentsAttr> attrList = equipmentsAttrDao.selectListByEquipmentCode(equipmentCode);// 根据设备编码查询设备属性
			for (EquipmentsAttr attr : attrList) {
				if (attr.getCustomTag() != null && attr.getCustomTag() != "") {
					map.put(attr.getCustomTag(), attr.getValue());
				}
			}
			equipment.setConfigs(map);
		}
		return list;
	}

	@Override
	public Page<Equipments> selectEqInfoBySectionCode(Equipments equipments, int index, int size) {
		PageHelper.startPage(index, size);
		Page<Equipments> list = (Page<Equipments>) equipmentsDao.selectEqInfoBySectionCode(equipments);// 查询非情报板类型的设备
		for (Equipments equipment : list) {
			Map<String, Object> map = new HashMap<String, Object>();
			String equipmentCode = equipment.getCode();// 获取设备编码
			List<EquipmentsAttr> attrList = equipmentsAttrDao.selectListByEquipmentCode(equipmentCode);// 根据设备编码查询设备属性
			for (EquipmentsAttr attr : attrList) {
				if (attr.getCustomTag() != null && attr.getCustomTag() != "") {
					map.put(attr.getCustomTag(), attr.getValue());
				}
			}
			equipment.setConfigs(map);
		}
		return list;
	}

	@Override
	public List<Equipments> selectEquimentClassifyInfo(Equipments equipments2) {
		return equipmentsDao.selectEquimentClassifyInfo(equipments2);
	}

	@Override
	public List<Equipments> selectEquimentClassifyInfos(Equipments equipments2) {
		return equipmentsDao.selectEquimentClassifyInfos(equipments2);
	}

	@Override
	public Page<Equipments> selectEquipmentsBySeCode(Equipments equipments, int index, int size) {
		PageHelper.startPage(index, size);
		List<Equipments> list = equipmentsDao.selectEquipmentsBySeCode(equipments);
		return (Page<Equipments>) list;
	}

	/**
	 * 设备在线情况接口方法判断
	 */
	@Override
	public List<Equipments> selectEquiClassifyAndEquipments(Equipments equipments) {
		StringBuilder sb = null;
		List<Equipments> classifyInfo = equipmentsDao.selectEquimentClassifyInfo(equipments); // 查询所有的设备分类
		Jedis redis = null;
		try {
			redis = jedisPool.getResource();
			for (Equipments equimentClassify : classifyInfo) {
				// 判断横洞卷帘门的情况 HDJIM
				if (equimentClassify != null && CommonUtils.isNotEmpty(equimentClassify.getCategoryCode())
						&& "HDJIM".equals(equimentClassify.getCategoryCode())) {  //针对内邓情况卷帘门没接入,但一直有反馈数据
					List<Equipments> equiList = equipmentsDao.selectEquipmentsByEquiClassify(
							equimentClassify.getCategoryCode(), equipments.getType(), equipments.getSectionCode());
					Map<String, Object> indexTypeMap = null;
					for (Equipments equMdoel : equiList) {
						boolean isOffline = false;// 离线
						boolean isStop = false;// 停机
						boolean isNormal = false;// 在线
						indexTypeMap = new HashMap<>();
						List<EquipmentPoints> HdjlmEquPointsList = equipmentPointsDao
								.selectPointsByEquCodeAndFeedback(equMdoel.getCode(), CommonUtils.FEEDBACK_YES);
						String indexType;
						for (int i = 0; i < HdjlmEquPointsList.size(); i++) {
							sb = new StringBuilder();
							sb.append(POINT_NAME).append(HdjlmEquPointsList.get(i).getCode()).append(VALUE_NAME);
							String value = redis.lindex(sb.toString(), 0);
							if (value != null) {
								value = value.replace(" ", "");
								String[] valueArray = value.split(REALTIME_SPLITTER_LEVEL1);
								/**
								 * 判断实时redis中的第一条数据时间和当前时间相差是否大于60s
								 */
								long timeout = 0L;
								if (valueArray[0].length() > 11) {
									timeout = (System.currentTimeMillis() - Long.parseLong(valueArray[0]))
											/ REALTIME_TIME_OUT_MILL;
								} else {
									timeout = ((System.currentTimeMillis() / 1000) - Long.parseLong(valueArray[0]));
								}
								if (timeout < REALTIME_TIME_OUT_SECOND) {
									HdjlmEquPointsList.get(i).setTime(Long.parseLong(valueArray[0]));
									HdjlmEquPointsList.get(i).setValue(Float.parseFloat(valueArray[1]));
								} else {
									HdjlmEquPointsList.get(i).setTime(Long.parseLong(valueArray[0]));
									HdjlmEquPointsList.get(i).setValue(-1);
								}
							}
							indexType = HdjlmEquPointsList.get(i).getIndexType();
							indexTypeMap.put(indexType,
									HdjlmEquPointsList.get(i).getValue() != null ? HdjlmEquPointsList.get(i).getValue()
											: -1);
						}
						equMdoel.setIndexType(indexTypeMap);
						if (JudgeNullUtil.iMap(indexTypeMap)) {
							String indexValue = "";
							for (Object mapValue : indexTypeMap.values()) {
								indexValue = String.valueOf(mapValue);
								if (Double.valueOf(indexValue).intValue() == -1) {
									isOffline = true;
								} else if (Double.valueOf(indexValue).intValue() == 0) {
									isStop = true;
								} else {
									isNormal = true;
								}
							}
							if (isNormal) {// 如果在线
								equMdoel.setCurrentState(CommonUtils.EQU_STATE_NORMAL);
							} else if (isStop) {// 如果停机
								// equMdoel.setCurrentState(CommonUtils.EQU_STATE_OFFLINE);
								equMdoel.setCurrentState(-1);
							} else if (isOffline) {// 如果离线
								equMdoel.setCurrentState(-1);
							}
						}
					}
					equimentClassify.setEquipmensInfo(equiList);
				} else { // 判断其他设备的情况
					List<Equipments> equiList = equipmentsDao.selectEquipmentsByEquiClassify(
							equimentClassify.getCategoryCode(), equipments.getType(), equipments.getSectionCode());
					Map<String, Object> indexTypeMap = null;
					for (Equipments equMdoel : equiList) {
						boolean isOffline = false;// 离线
						boolean isStop = false;// 停机
						boolean isNormal = false;// 在线
						indexTypeMap = new HashMap<>();
						if (equMdoel != null && CommonUtils.isNotEmpty(equMdoel.getCategoryCode())
								&& (equMdoel.getCategoryCode().equals(EquipmentsCategoriesLogicImpl.CATE_CDZSQ)
										|| equMdoel.getCategoryCode().equals(EquipmentsCategoriesLogicImpl.CATE_HDZSQ)
										|| equMdoel.getCategoryCode()
												.equals(EquipmentsCategoriesLogicImpl.CATE_GQJCQ))) {
							List<EquipmentsAttr> equAttrList = equipmentsAttrDao
									.selectListByEquipmentCode(equMdoel.getCode());
							equMdoel.setEquipmentsAttr(equAttrList);
						}
						// List<EquipmentPoints> equPointsList =
						// equipmentPointsDao.selectPointsByEquCode(equMdoel.getCode());
						List<EquipmentPoints> equPointsList = equipmentPointsDao
								.selectPointsByEquCodeAndFeedback(equMdoel.getCode(), CommonUtils.FEEDBACK_YES);
						String indexType;
						for (int i = 0; i < equPointsList.size(); i++) {
							sb = new StringBuilder();
							sb.append(POINT_NAME).append(equPointsList.get(i).getCode()).append(VALUE_NAME);
							String value = redis.lindex(sb.toString(), 0);
							if (value != null) {
								value = value.replace(" ", "");
								String[] valueArray = value.split(REALTIME_SPLITTER_LEVEL1);
								/**
								 * 判断实时redis中的第一条数据时间和当前时间相差是否大于60s
								 */
								long timeout = 0L;
								if (valueArray[0].length() > 11) {
									timeout = (System.currentTimeMillis() - Long.parseLong(valueArray[0]))
											/ REALTIME_TIME_OUT_MILL;
								} else {
									timeout = ((System.currentTimeMillis() / 1000) - Long.parseLong(valueArray[0]));
								}
								if (timeout < REALTIME_TIME_OUT_SECOND) {
									equPointsList.get(i).setTime(Long.parseLong(valueArray[0]));
									equPointsList.get(i).setValue(Float.parseFloat(valueArray[1]));
								} else {
									equPointsList.get(i).setTime(Long.parseLong(valueArray[0]));
									equPointsList.get(i).setValue(-1);
								}
							}
							/*
							 * indexTypeMap.put(equPointsList.get(i).getIndexType(),
							 * equPointsList.get(i).getValue() != null ? equPointsList.get(i).getValue() :
							 * 0);
							 */
							indexType = equPointsList.get(i).getIndexType();
							indexTypeMap.put(indexType,
									equPointsList.get(i).getValue() != null ? equPointsList.get(i).getValue() : -1);
						}
						equMdoel.setIndexType(indexTypeMap);
						if (JudgeNullUtil.iMap(indexTypeMap)) {
							String indexValue = "";
							for (Object mapValue : indexTypeMap.values()) {
								indexValue = String.valueOf(mapValue);
								if (Double.valueOf(indexValue).intValue() == -1) {
									isOffline = true;
								} else if (Double.valueOf(indexValue).intValue() == 0) {
									isStop = true;
								} else {
									isNormal = true;
								}
							}
							if (isNormal) {// 如果在线
								equMdoel.setCurrentState(CommonUtils.EQU_STATE_NORMAL);
							} else if (isStop) {// 如果停机
								equMdoel.setCurrentState(CommonUtils.EQU_STATE_NORMAL);
							} else if (isOffline) {// 如果离线
								equMdoel.setCurrentState(-1);
							}
						}
					}
					equimentClassify.setEquipmensInfo(equiList);
				}
			}
		} catch (JedisException e) {
			LOG.error("selectEquiClassifyAndEquipments is error, data : {}, error: {}", equipments, e);
		} finally {
			jedisPool.returnResource(redis);
		}
		return classifyInfo;
	}

	@Override
	public List<Equipments> selectEquiClassifyTreeAndEquipmentsTree(Equipments equipments) {
		List<Equipments> classifyInfo = equipmentsDao.selectEquimentClassifyInfo(equipments);
		for (Equipments equipments2 : classifyInfo) {
			List<TreeObject> list = new ArrayList<TreeObject>();
			TreeObject treeModel = null;
			List<Equipments> equiList = equipmentsDao.selectEquipmentsByEquiClassify(equipments2.getCategoryCode(),
					equipments.getType(), equipments.getSectionCode());
			for (int i = 0; i < equiList.size(); i++) {
				treeModel = new TreeObject();
				treeModel.setId(equiList.get(i).getCode());
				treeModel.setIndexId(equiList.get(i).getId());
				treeModel.setParentId(equiList.get(i).getParentId() + 1);
				treeModel.setSelectId(equiList.get(i).getId());
				treeModel.setCode(equiList.get(i).getCode());
				treeModel.setName(equiList.get(i).getName());
				treeModel.setText(equiList.get(i).getName());
				treeModel.setLocation(equiList.get(i).getLocation());
				treeModel.setLocations(equiList.get(i).getLocations());
				treeModel.setGrade(1);
				list.add(treeModel);
			}
			equipments2.setChildren(list);
		}
		return classifyInfo;
	}

	@Override
	public List<Equipments> selectEquipmentsByName(Equipments equipments) {
		return equipmentsDao.selectEquipmentsByName(equipments);
	}

	@Override
	public Equipments selectEquipmentsByCode(Equipments equipments) {
		return equipmentsDao.selectEquipmentsByCode(equipments);
	}

	/**
	 * 查询所有隧道和隧道下的摄像机设备设备
	 */
	@Override
	public List<Equipments> selectCameraEquipmentsBySeCode() {
		// 查询所有的隧道分类
		List<Equipments> allClassifyTunnel = equipmentsDao.selectAllClassifyTunnel();
		for (Equipments equipment : allClassifyTunnel) {
			// 查询隧道下有多少个横洞卷帘门(是带左转车道指示器的数量的一半)
			int hdCount = equipmentsDao.selectHDCount(equipment) / 2;
			equipment.setHdCount(hdCount);
			// 添加摄像机类型
			equipment.setCategoryCode("QSSXT");
			// 查询该隧道下对应标识的所有摄像机信息
			List<Equipments> cameraEquipmentsRight = equipmentsDao.selectRightCameraEquipments(equipment);
			equipment.setEquipmensRight(cameraEquipmentsRight);
			List<Equipments> cameraEquipmentsLeft = equipmentsDao.selectLeftCameraEquipments(equipment);
			equipment.setEquipmensLeft(cameraEquipmentsLeft);
		}
		return allClassifyTunnel;
	}

	/**
	 * 查询设备code所在的区域
	 */
	@Override
	public Equipments selectEquipArea(EquipmentsAttr equipmentsAttr) {
		return equipmentsDao.selectEquipArea(equipmentsAttr);
	}

	@Override
	public Equipments selectPositionByCode(EquipmentsAttr equipmentsAttr) {
		return equipmentsDao.selectPositionByCode(equipmentsAttr);
	}

	@Override
	public List<Equipments> selectEquipsBySectionAndCategory(Equipments equipments) {
		return equipmentsDao.selectEquipsBySectionAndCategory(equipments);
	}

	@Override
	public List<Equipments> selectCameraAreaEquipments(Equipments equipments) {
		List<Equipments> cameraAreaEquipments = new ArrayList<>();
		String pileRange = "";
		// 先查隧道右洞的摄像设备的信息
		equipments.setCategoryCode("QSSXT");
		List<Equipments> rightCameraEquipments = equipmentsDao.selectRightCameraEquipments(equipments);
		for (int i = 0; i < rightCameraEquipments.size(); i++) {
			if (i < rightCameraEquipments.size() - 1) {
				pileRange = rightCameraEquipments.get(i).getPileNo() + "|"
						+ rightCameraEquipments.get(i + 1).getPileNo();
				rightCameraEquipments.get(i).setPileRange(pileRange);
			} else {
				String pileNo1 = rightCameraEquipments.get(0).getPileNo();
				String pileNo2 = rightCameraEquipments.get(1).getPileNo();
				String lastPile = rightCameraEquipments.get(i).getPileNo();
				String endPile = getPileRange(pileNo1, pileNo2, lastPile);
				pileRange = rightCameraEquipments.get(i).getPileNo() + "|" + endPile;
				rightCameraEquipments.get(i).setPileRange(pileRange);
			}
			cameraAreaEquipments.add(rightCameraEquipments.get(i));
		}
		// 再查隧道左洞的摄像设备信息
		List<Equipments> leftCameraEquipments = equipmentsDao.selectLeftCameraEquipments(equipments);
		for (int i = leftCameraEquipments.size() - 1; i >= 0; i--) {
			if (i != 0) {
				pileRange = leftCameraEquipments.get(i - 1).getPileNo() + "|" + leftCameraEquipments.get(i).getPileNo();
				leftCameraEquipments.get(i).setPileRange(pileRange);
			} else {
				String pileNo1 = leftCameraEquipments.get(1).getPileNo();
				String pileNo2 = leftCameraEquipments.get(2).getPileNo();
				String lastPile = leftCameraEquipments.get(i).getPileNo();
				String startPile = getPileRange(pileNo1, pileNo2, lastPile);
				pileRange = startPile + "|" + leftCameraEquipments.get(i).getPileNo();
				leftCameraEquipments.get(i).setPileRange(pileRange);
			}
			cameraAreaEquipments.add(leftCameraEquipments.get(i));
		}
		return cameraAreaEquipments;
	}

	/**
	 * 根据传入的桩号获取结束或者开始的桩号
	 * 
	 * @param pile1
	 * @param pile2
	 * @param lastPile
	 * @return
	 */
	public String getPileRange(String pile1, String pile2, String lastPile) {
		String pileEnd = "";
		if (pile1.startsWith("k") && pile2.startsWith("k") && lastPile.startsWith("k")) {
			String[] arrayPile1 = pile1.replace("k", "").split("\\+");
			String[] arrayPile2 = pile2.replace("k", "").split("\\+");
			String[] arrayPile3 = lastPile.replace("k", "").split("\\+");
			if (arrayPile1.length >= 2 && arrayPile2.length >= 2 && arrayPile3.length >= 2) {
				int pile1Num = Integer.parseInt(arrayPile1[0]) * 1000 + Integer.parseInt(arrayPile1[1]);
				int pile2Num = Integer.parseInt(arrayPile2[0]) * 1000 + Integer.parseInt(arrayPile2[1]);
				int pile3Num = Integer.parseInt(arrayPile3[0]) * 1000 + Integer.parseInt(arrayPile3[1]);
				int left = (pile3Num + (pile2Num - pile1Num + 50)) / 1000;
				int right = (pile3Num + (pile2Num - pile1Num + 50)) % 1000;
				pileEnd = "k" + left + "+" + right;
			}
		}
		if (pile1.startsWith("zk") && pile2.startsWith("zk") && lastPile.startsWith("zk")) {
			String[] arrayPile1 = pile1.replace("zk", "").split("\\+");
			String[] arrayPile2 = pile2.replace("zk", "").split("\\+");
			String[] arrayPile3 = lastPile.replace("zk", "").split("\\+");
			if (arrayPile1.length >= 2 && arrayPile2.length >= 2 && arrayPile3.length >= 2) {
				int pile1Num = Integer.parseInt(arrayPile1[0]) * 1000 + Integer.parseInt(arrayPile1[1]);
				int pile2Num = Integer.parseInt(arrayPile2[0]) * 1000 + Integer.parseInt(arrayPile2[1]);
				int pile3Num = Integer.parseInt(arrayPile3[0]) * 1000 + Integer.parseInt(arrayPile3[1]);
				int left = (pile3Num + (pile2Num - pile1Num - 50)) / 1000;
				int right = (pile3Num + (pile2Num - pile1Num - 50)) % 1000;
				pileEnd = "zk" + left + "+" + right;
			}
		}
		return pileEnd;
	}

	@Override
	public List<Equipments> selectTriggerEquipmentsBySection(Equipments equipments) {
		// 由sectionCode的值查询该隧道下的触发设备的分类
		List<String> categorys = new ArrayList<>();
		categorys.add(SDBJAN); // 手动火灾报警
		categorys.add(FBSGWGX); // 感温光纤报警
		categorys.add(SBCHZTCQ); // 双波长探测器报警
		String areaId = equipments.getAreaId();
		String sectionCode = equipments.getSectionCode();
		List<Equipments> TrrigerClassEquipments = equipmentsDao.selectTrrigerClassEquipments(categorys, areaId,
				sectionCode);
		for (Equipments equipment : TrrigerClassEquipments) {
			equipment.setAreaId(equipments.getAreaId());
			List<Equipments> TriggerEquipments = equipmentsDao.selectTriggerEquipmentsBySection(equipment);
			equipment.setEquipmensInfo(TriggerEquipments);
		}
		return TrrigerClassEquipments;
	}

	@Override
	public boolean insertEquipmentArea(EquipmentArea equipmentArea) {
		List<Integer> allResults = new ArrayList<>();
		boolean flag = true;
		if (equipmentArea != null) {
			String triggerEquipments = equipmentArea.getTriggerEquipments();
			if (JudgeNullUtil.iStr(triggerEquipments)) {
				List<Equipments> triggerListEquipment = JSON.parseArray(triggerEquipments, Equipments.class);
				for (Equipments equipment : triggerListEquipment) {
					EquipmentArea area = new EquipmentArea();
					area = equipmentArea;
					String code = equipment.getCode();
					String createTime = System.currentTimeMillis() + "";
					area.setEquipmentCode(code);
					area.setStatus(1);
					area.setCreateTime(createTime);
					// 添加之前,先进行查询
					List<EquipmentArea> selectAreas = equipmentsDao.selectEquipmentArea(area);
					if (!JudgeNullUtil.iList(selectAreas)) {
						int result = equipmentsDao.insertEquipmentArea(area);
						allResults.add(result);
					} else {
						for (EquipmentArea equipmentAreaSelect : selectAreas) {
							equipmentsDao.deleteEquipmentArea(equipmentAreaSelect);
						}
						int result = equipmentsDao.insertEquipmentArea(area);
						allResults.add(result);
					}
				}
			} else {
				LOG.warn("添加监控区域下的触发设备为空!");
			}
		} else {
			LOG.warn("添加监控区域和触发设备的关联关系时,添加数据都为空!");
		}
		for (Integer num : allResults) {
			if (num != 1) {
				flag = false;
			}
		}
		return flag;
	}

	@Override
	public boolean deleteEquipmentArea(EquipmentArea equipmentArea) {
		boolean flag = false;
		int result = equipmentsDao.deleteEquipmentArea(equipmentArea);
		if (result != 0) {
			flag = true;
		}
		return flag;
	}

	@Override
	public boolean updateEquipmentArea(EquipmentArea equipmentArea) {
		List<Integer> allResults = new ArrayList<>();
		boolean flag = true;
		// 先删除对应的监控区域关联关系
		if (equipmentArea != null) {
			int result = equipmentsDao.deleteEquipmentArea(equipmentArea);
			if (result != 0) {
				String triggerEquipments = equipmentArea.getTriggerEquipments();
				if (JudgeNullUtil.iStr(triggerEquipments)) {
					List<Equipments> triggerListEquipment = JSON.parseArray(triggerEquipments, Equipments.class);
					for (Equipments equipment : triggerListEquipment) {
						EquipmentArea area = new EquipmentArea();
						area = equipmentArea;
						String code = equipment.getCode();
						String createTime = System.currentTimeMillis() + "";
						area.setEquipmentCode(code);
						area.setStatus(1);
						area.setCreateTime(createTime);
						int num = equipmentsDao.insertEquipmentArea(area);
						allResults.add(num);
					}
				} else {
					LOG.warn("更新监控区域下的触发设备为空!");
				}
			} else {
				LOG.warn("更新监控区域时,删除原先的区域为空,请检查数据信息!");
			}
		} else {
			LOG.warn("更新监控区域时,传入的参数为空,请检查数据信息!");
		}
		for (Integer num : allResults) {
			if (num != 1) {
				flag = false;
			}
		}
		return flag;
	}

	@Override
	public List<EquipmentArea> selectEquipmentAreaSection() {
		List<EquipmentArea> equipmentAreaSection = equipmentsDao.selectEquipmentAreaSection();
		for (EquipmentArea equipmentArea : equipmentAreaSection) {
			String code = equipmentArea.getSectionCode();
			Section section = sectionDao.selectSectionByCode(code);
			equipmentArea.setSectionName(section.getName());
		}
		return equipmentAreaSection;
	}

	@Override
	public Page<EquipmentArea> selectEquipmentArea(EquipmentArea equipmentArea, int index, int size) {
		List<Equipments> triggerListEquipment = null;
		List<EquipmentArea> cameraAreas = null;
		PageHelper.startPage(index, size);
		// 没有传入隧道信息时,查询监控区域和触发设备关联关系表的所有信息
		if (!JudgeNullUtil.iStr(equipmentArea.getSectionCode())&&!JudgeNullUtil.iStr(equipmentArea.getSectionName())) { 
			equipmentArea = new EquipmentArea();
			cameraAreas = equipmentsDao.selectCameraArea(equipmentArea);
			if (JudgeNullUtil.iList(cameraAreas)) {
				for (EquipmentArea cameraArea : cameraAreas) {
					triggerListEquipment = new ArrayList<>();
					Equipments cameraEquipment = equipmentsDao.selectCameraName(cameraArea.getCameraCode());
					List<EquipmentArea> selectEquipmentArea = equipmentsDao.selectEquipmentArea(cameraArea);
					if (JudgeNullUtil.iList(selectEquipmentArea)) {
						for (EquipmentArea equipmentAreaSelect : selectEquipmentArea) {
							String equipmentCode = equipmentAreaSelect.getEquipmentCode();
							// 根据EquipmentArea的equipmentCode查询设备信息
							Equipments triggerEquipment = equipmentsDao.selectSingleEquipmentByEquCode(equipmentCode);
							triggerListEquipment.add(triggerEquipment);
						}
						// 返回结果中添加的字段
						cameraArea.setTriggerListEquipment(triggerListEquipment);
						cameraArea.setCameraName(cameraEquipment.getName());
					} else {
						LOG.warn("摄像机区域下没有关联触发设备!");
					}
				}
			} else {
				LOG.warn("该隧道下没有添加过监控区域!");
			}
		} else { // 选中隧道后,查询执行流程
			String sectionName = "";
			if (equipmentArea.getSectionName() == null && equipmentArea.getSectionCode() != null) {
				sectionName = equipmentsDao.selectSectionName(equipmentArea.getSectionCode());
			} else {
				sectionName = equipmentArea.getSectionName();
			}
			// 查该隧道的区域
			cameraAreas = equipmentsDao.selectCameraArea(equipmentArea);
			// 通过单个监控区域查询摄像机和触发设备的关联关系
			if (JudgeNullUtil.iList(cameraAreas)) {
				for (EquipmentArea cameraArea : cameraAreas) {
					triggerListEquipment = new ArrayList<>();
					Equipments cameraEquipment = equipmentsDao.selectCameraName(cameraArea.getCameraCode());
					List<EquipmentArea> selectEquipmentArea = equipmentsDao.selectEquipmentArea(cameraArea);
					if (JudgeNullUtil.iList(selectEquipmentArea)) {
						for (EquipmentArea equipmentAreaSelect : selectEquipmentArea) {
							String equipmentCode = equipmentAreaSelect.getEquipmentCode();
							// 根据EquipmentArea的equipmentCode查询设备信息
							Equipments triggerEquipment = equipmentsDao.selectSingleEquipmentByEquCode(equipmentCode);
							triggerListEquipment.add(triggerEquipment);
						}
						// 返回结果中添加的字段
						cameraArea.setTriggerListEquipment(triggerListEquipment);
						cameraArea.setSectionName(sectionName);
						cameraArea.setCameraName(cameraEquipment.getName());
					} else {
						LOG.warn("摄像机区域下没有关联触发设备!");
					}
				}
			} else {
				LOG.warn("该隧道下没有添加过监控区域!");
			}
		}
		if (JudgeNullUtil.iList(cameraAreas)) {
			return (Page<EquipmentArea>) cameraAreas;
		} else {
			return null;
		}
	}

	@Override
	public EquipmentArea selectSignleEquipmentArea(EquipmentArea equipmentArea) {
		String sectionName = "";
		List<Equipments> triggerListEquipment = new ArrayList<>();
		if (equipmentArea.getSectionName() == null && equipmentArea.getSectionCode() != null) {
			sectionName = equipmentsDao.selectSectionName(equipmentArea.getSectionCode());
		} else {
			sectionName = equipmentArea.getSectionName();
		}
		Equipments cameraEquipment = equipmentsDao.selectCameraName(equipmentArea.getCameraCode());
		List<EquipmentArea> selectEquipmentArea = equipmentsDao.selectEquipmentArea(equipmentArea);
		if (JudgeNullUtil.iList(selectEquipmentArea)) {
			for (EquipmentArea equipmentAreaSelect : selectEquipmentArea) {
				String equipmentCode = equipmentAreaSelect.getEquipmentCode();
				// 根据EquipmentArea的equipmentCode查询设备信息
				Equipments triggerEquipment = equipmentsDao.selectSingleEquipmentByEquCode(equipmentCode);
				triggerListEquipment.add(triggerEquipment);
			}
			// 返回结果中添加的字段
			equipmentArea.setTriggerListEquipment(triggerListEquipment);
			equipmentArea.setSectionName(sectionName);
			equipmentArea.setCameraName(cameraEquipment.getName());
			equipmentArea.setAreaId(cameraEquipment.getAreaId());
			String pileNo = cameraEquipment.getPileNo();
			String endPileNo = "";
			if (pileNo.startsWith("k")) {
				endPileNo = getEndPileNo(pileNo);
				equipmentArea.setPileRange(pileNo + "|" + endPileNo);
			} else if (pileNo.startsWith("zk")) {
				endPileNo = getEndPileNo(pileNo);
				equipmentArea.setPileRange(endPileNo + "|" + pileNo);
			}
		} else {
			LOG.warn("摄像机区域下没有关联触发设备!");
		}

		return equipmentArea;
	}

	/**
	 * 获取摄像机区域结束的桩号
	 * 
	 * @param startPileNo
	 * @return
	 */
	public String getEndPileNo(String startPileNo) {
		String endPileNo = "";
		if (startPileNo.startsWith("k")) {
			String[] arrayPile = startPileNo.replace("k", "").split("\\+");
			int pileNum = Integer.parseInt(arrayPile[0]) * 1000 + Integer.parseInt(arrayPile[1]);
			int left = (pileNum + 150) / 1000;
			int right = (pileNum + 150) % 1000;
			endPileNo = "k" + left + "+" + right;
		} else if (startPileNo.startsWith("zk")) {
			String[] arrayPile = startPileNo.replace("zk", "").split("\\+");
			int pileNum = Integer.parseInt(arrayPile[0]) * 1000 + Integer.parseInt(arrayPile[1]);
			int left = (pileNum - 150) / 1000;
			int right = (pileNum - 150) % 1000;
			endPileNo = "zk" + left + "+" + right;
		}
		return endPileNo;
	}

	/**
	 * 查询所有的隧道信息和隧道下的事故区域
	 */
	@Override
	public List<Equipments> selectAllClassifyTunnelsAndAccidentArea() {
		// 查询所有的隧道分类
		List<Equipments> allClassifyTunnel = equipmentsDao.selectAllClassifyTunnel();
		//声明左洞序号变量
		int left = 0;
		//声明右洞序号变量
		int right = 0;
		for (Equipments equipment : allClassifyTunnel) {
			// 查询隧道下有多少个横洞卷帘门(是带左转车道指示器的数量的一半),给隧道赋设备分类值
			equipment.setCategoryCode("CDZSQ");
			int hdCount = equipmentsDao.selectHDCount(equipment) / 2;
			equipment.setHdCount(hdCount);
			
			// 查询隧道下的右洞的事故区域
			List<Equipments> accidentAreaIds = equipmentsDao.selectAccidentAreaId(equipment);
			for (Equipments accidentAreaId : accidentAreaIds) {
				// 添加摄像机类型
				accidentAreaId.setCategoryCode("QSSXT");
				// 查询该隧道下对应标识的所有摄像机信息,右洞
				List<Equipments> cameraEquipmentsRight = equipmentsDao.selectRightCameraEquipments(accidentAreaId);
				if (JudgeNullUtil.iList(cameraEquipmentsRight)) {
					for (int i = 0; i < cameraEquipmentsRight.size(); i++) {
						right++;
						cameraEquipmentsRight.get(i).setAlias("R" + right);
					}
					accidentAreaId.setEquipmensRight(cameraEquipmentsRight);
				}
				
				//左洞
				List<Equipments> cameraEquipmentsLeft = equipmentsDao.selectLeftCameraEquipments(accidentAreaId);
				if (JudgeNullUtil.iList(cameraEquipmentsLeft)) {
					for (int i = 0; i < cameraEquipmentsLeft.size(); i++) {
						left++;
						cameraEquipmentsLeft.get(i).setAlias("L" + left);
					}
					accidentAreaId.setEquipmensLeft(cameraEquipmentsLeft);
				}
			}
			equipment.setEquipmensInfo(accidentAreaIds);
		}
		return allClassifyTunnel;
	}

	@Override
	public List<EquipmentArea> selectCameraAreaAndTriggerEquipment(Equipments equipments) {
		List<EquipmentArea> equipmentAreas = new ArrayList<>();
		List<Equipments> triggerListEquipment = null;
		//为查询条件添加枪式摄像头信息
		equipments.setCategoryCode("QSSXT");
		List<Equipments> cameraAreaEquipments = equipmentsDao.selectCameraAreaBySection(equipments);
		if (JudgeNullUtil.iList(cameraAreaEquipments)) {
			for (Equipments cameraEquipment : cameraAreaEquipments) { //把查询到的摄像机设备转换成监控区域
				EquipmentArea equipmentArea = new EquipmentArea();
				equipmentArea.setCameraCode(cameraEquipment.getCode());
				equipmentArea.setCameraName(cameraEquipment.getEquipmentName());
				equipmentArea.setSectionCode(cameraEquipment.getSectionCode());
				equipmentAreas.add(equipmentArea);
			}
		}
		if (JudgeNullUtil.iList(cameraAreaEquipments)) {
			for (EquipmentArea equipmentArea : equipmentAreas) {
				triggerListEquipment = new ArrayList<>();
				List<EquipmentArea> selectEquipmentArea = equipmentsDao.selectEquipmentArea(equipmentArea);
				if (JudgeNullUtil.iList(selectEquipmentArea)) {
					for (EquipmentArea equipmentAreaSelect : selectEquipmentArea) {
						String equipmentCode = equipmentAreaSelect.getEquipmentCode();
						// 根据EquipmentArea的equipmentCode查询设备信息
						if (equipmentCode != null) {
							Equipments triggerEquipment = equipmentsDao.selectSingleEquipmentByEquCode(equipmentCode);
							if (triggerEquipment != null) {
								triggerListEquipment.add(triggerEquipment);
							}
						}
					}
					// 返回结果中添加的字段
					equipmentArea.setTriggerListEquipment(triggerListEquipment);
				}
			}
		}
		return equipmentAreas;
	}

	@Override
	public List<Equipments> selectEquiClassifyAndAreaId(Equipments equipments) {
		StringBuilder sb = null;
		// 查询所有的设备分类
		List<Equipments> classifyInfo = equipmentsDao.selectEquimentClassifyInfo(equipments); //categoryCode,sectionCode,
		Jedis redis = null;
		try {
			redis = jedisPool.getResource();
			for (Equipments equimentClassify : classifyInfo) {
				//查询单个分类所属的事故区域
				List<Equipments> categoryWithAreaId = equipmentsDao.selectAreaIdByCategory(equimentClassify);
				for (Equipments categoryEquipment : categoryWithAreaId) {
					
					//查询车道指示器所在事故区域的车道数
					if (categoryEquipment.getCategoryCode().contains("CDZSQ")) {
						List<String> lanes = new ArrayList<>();
						List<Equipments> laneEquipments = equipmentsDao.selectLanesBySection(categoryEquipment);
						for (Equipments laneEquipment : laneEquipments) {
							if (laneEquipment.getLane() != null) {
								lanes.add(laneEquipment.getLane());
							}
						}
						categoryEquipment.setLanes(lanes);
					}
					
					List<Equipments> listEquipment = null;
					//查询该分类该事故区域下的一个设备属性
					List<Equipments> equiList = equipmentsDao.selectEquipmentsByEquiClassify(
							categoryEquipment.getCategoryCode(), equipments.getType(), equipments.getSectionCode());
					Map<String, Object> indexTypeMap = null;
					for (int j = 0; j < equiList.size(); j++) {
						listEquipment = new ArrayList<>();
						indexTypeMap = new HashMap<>();
						if (equiList.get(j) != null && CommonUtils.isNotEmpty(equiList.get(j).getCategoryCode())
								&& (equiList.get(j).getCategoryCode().equals(EquipmentsCategoriesLogicImpl.CATE_CDZSQ)
										|| equiList.get(j).getCategoryCode().equals(EquipmentsCategoriesLogicImpl.CATE_HDZSQ)
										|| equiList.get(j).getCategoryCode()
										.equals(EquipmentsCategoriesLogicImpl.CATE_GQJCQ))) {
							List<EquipmentsAttr> equAttrList = equipmentsAttrDao
									.selectListByEquipmentCode(equiList.get(j).getCode());
							equiList.get(j).setEquipmentsAttr(equAttrList);
						}
						List<EquipmentPoints> equPointsList = equipmentPointsDao
								.selectPointsByEquCodeAndFeedback(equiList.get(j).getCode(), CommonUtils.FEEDBACK_YES);
						String indexType;
						for (int i = 0; i < equPointsList.size(); i++) {
							sb = new StringBuilder();
							sb.append(POINT_NAME).append(equPointsList.get(i).getCode()).append(VALUE_NAME);
							String value = redis.lindex(sb.toString(), 0);
							if (value != null) {
								value = value.replace(" ", "");
								String[] valueArray = value.split(REALTIME_SPLITTER_LEVEL1);
								/**
								 * 判断实时redis中的第一条数据时间和当前时间相差是否大于60s
								 */
								long timeout = 0L;
								if (valueArray[0].length() > 11) {
									timeout = (System.currentTimeMillis() - Long.parseLong(valueArray[0]))
											/ REALTIME_TIME_OUT_MILL;
								} else {
									timeout = ((System.currentTimeMillis() / 1000) - Long.parseLong(valueArray[0]));
								}
								if (timeout < REALTIME_TIME_OUT_SECOND) {
									equPointsList.get(i).setTime(Long.parseLong(valueArray[0]));
									equPointsList.get(i).setValue(Float.parseFloat(valueArray[1]));
								} else {
									equPointsList.get(i).setTime(Long.parseLong(valueArray[0]));
									equPointsList.get(i).setValue(-1);
								}
							}
							indexType = equPointsList.get(i).getIndexType();
							indexTypeMap.put(indexType,
									equPointsList.get(i).getValue() != null ? equPointsList.get(i).getValue() : -1);
						}
						equiList.get(j).setIndexType(indexTypeMap);
						listEquipment.add(equiList.get(0));
						break; //只取该分类的一个设备数据
					}
					categoryEquipment.setEquipmensInfo(listEquipment);
				}
				equimentClassify.setEquipmensInfo(categoryWithAreaId);
			}
		}catch(JedisException e){
			LOG.error("selectEquiClassifyAndEquipments is error, data : {}, error: {}", equipments, e);
		}finally{
			jedisPool.returnResource(redis);
		}
		return classifyInfo;
	}

	@Override
	public List<Equipments> selectEquipsBySectionAndCategoryAndLaneAndAreaId(Equipments equipments) {
		return equipmentsDao.selectEquipsBySectionAndCategoryAndLaneAndAreaId(equipments);
	}

}
 